﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MatrixWebApiCore.Common
{
    public class MessageHelper
    {

        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="info"></param>
        public static void LogInfo(string info)
        {
//#if DEBUG
            Console.WriteLine(info);
//#endif
            AddLog(info);
        }
        /// <summary>
        /// 记录异常日志
        /// </summary>
        /// <param name="info"></param>
        /// <param name="source"></param>
        public static void LogErrorInfo(string info)
        {
//#if DEBUG
            Console.WriteLine(info);
//#endif
            AddLog(info, true);
        }
        /// <summary>
        /// 记录异常日志
        /// </summary>
        /// <param name="info"></param>
        /// <param name="source"></param>
        public static void LogErrorInfo(string info, Exception ex)
        {
//#if DEBUG
            Console.WriteLine(info + "，" + ex.ToString());
//#endif
            AddLog(info + "," + ex.ToString(), true);
        }

        /// <summary>    
        /// 日志记录，写入txt文件    
        /// </summary>    
        /// <param name="msg">记录内容</param>    
        /// <returns></returns>    
        private static void AddLog(string msg, bool isError = false)
        {
            string saveFolder = "Log";//日志文件保存路径  
            if (isError)
            {
                saveFolder = "LogError";//错误日志记录文件夹
            }
            string tishiMsg = "";
            try
            {
                string fileName = DateTime.Now.ToString("yyyy-MM-dd");
                string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, saveFolder);
                if (Directory.Exists(filePath) == false)
                {
                    Directory.CreateDirectory(filePath);
                }
                string fileAbstractPath = filePath + "\\" + fileName + ".txt";
                FileStream fs = new FileStream(fileAbstractPath, FileMode.Append);
                StreamWriter sw = new StreamWriter(fs);
                //开始写入       
                string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                msg = time + ">" + msg + System.Environment.NewLine;

                sw.Write(msg);
                //清空缓冲区                 
                sw.Flush();
                //关闭流                 
                sw.Close();
                sw.Dispose();
                fs.Close();
                fs.Dispose();

                tishiMsg = "写入日志成功";
            }
            catch (Exception ex)
            {
                string datetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                tishiMsg = "[" + datetime + "]写入日志出错：" + ex.Message;
                Console.WriteLine(tishiMsg);
            }
        }

    }
}
